package com.gogowan.agroenterprise.supply;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.EnterpriseMaterial;
import com.gogowan.agroenterprise.model.FPhotoInfo;
import com.gogowan.agroenterprise.model.IntegrateQuestInfo;
import com.gogowan.agroenterprise.model.MaterialResultInfo;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.PicturesInfo;
import com.gogowan.agroenterprise.model.SupplyDemandDescInfo;
import com.gogowan.agroenterprise.model.SupplyDemandResultInfo;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.PicturesGridView;

/**
 * 发布供应信息
 * @author Administrator
 *
 */
public class PublishSupplyActivity extends BaseActivity{
	
	private EditText title;
	private EditText introduction;
	private Spinner productType;
	private EditText keywords;
	private EditText productInfo;
	private PicturesGridView picGrid;
	private Button release;
	//private Button myReleases;
	private Button datePicker;
	private String date;
	private ProgressDialog progressDialog;
	private SharedPreferences preferences;
	private List<EnterpriseMaterial> enterpriseMaterials;
	private EnterpriseMaterial selectedEnterpriseMaterial;  //选中的本公司产品类型
	private long enterpriseId;
	private List<FPhotoInfo> fPhotoInfos;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.supply_publish_supply);
		
		title = (EditText)findViewById(R.id.publish_supply_title);
		introduction = (EditText)findViewById(R.id.publish_supply_introduction);
		productType = (Spinner)findViewById(R.id.publish_supply_product_type);
		keywords = (EditText)findViewById(R.id.publish_supply_keywords);
		productInfo = (EditText)findViewById(R.id.publish_supply_product_info);
		datePicker = (Button)findViewById(R.id.publish_supply_dateBtn);
		picGrid = (PicturesGridView)findViewById(R.id.publish_supply_pic_grid);
		release = (Button)findViewById(R.id.publish_supply_release);
		//myReleases = (Button)findViewById(R.id.publish_supply_my_releases);
		
		preferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
		enterpriseId = preferences.getLong("enterpriseid", 0);
		
		String materials = preferences.getString("MaterialResultInfo", "");
		if (materials == null || materials.equals("")) {
			showFinishDialog("提示","初始化数据失败，请重新登录！");
		} else {
			MaterialResultInfo materialResultInfo = (MaterialResultInfo)Utils.fromJSON(materials, MaterialResultInfo.class);
			enterpriseMaterials = materialResultInfo.getMaterialList();
			
			if (enterpriseMaterials == null || enterpriseMaterials.size() == 0) {
				showFinishDialog("提示","初始化数据失败，请重新登录！");
			} else {
				String [] m1 = new String[enterpriseMaterials.size()];
				for (int i = 0; i < enterpriseMaterials.size(); i++) {
					m1[i] = enterpriseMaterials.get(i).getMaterialFullName();
				}
				
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(PublishSupplyActivity.this,android.R.layout.simple_spinner_item,m1);
				//设置下拉列表的风格
				 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				 //将adapter 添加到spinner中
				 productType.setAdapter(adapter);
				 
				 productType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> parent,View view, int position, long id) {
						
						selectedEnterpriseMaterial = enterpriseMaterials.get(position);
					}

					@Override
					public void onNothingSelected(AdapterView<?> parent) {
						selectedEnterpriseMaterial = null;
					}
				});
			}
		}
		
		release.setOnClickListener(releaseBtnCallback);
		//myReleases.setOnClickListener(myReleasesBtnCallback);
		datePicker.setOnClickListener(dateBtnCallback);
	}

	/**
	 * 发布供应按钮点击事件
	 */
	public Button.OnClickListener releaseBtnCallback = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			release.setEnabled(false);
			//文本框不能为空,重要字段为空或为0时不可提交
			SupplyDemandDescInfo supplyDemandDescInfo = new SupplyDemandDescInfo();
			
			if (title.getText().toString().trim() == null || title.getText().toString().trim().equals("")) {
				Toast.makeText(PublishSupplyActivity.this, "标题不可为空", Toast.LENGTH_LONG).show();
				release.setEnabled(true);
				return;
			} else {
				supplyDemandDescInfo.setTitle(title.getText().toString().trim());
			}
			
			if (introduction.getText().toString().trim() == null || introduction.getText().toString().trim().equals("")) {
				Toast.makeText(PublishSupplyActivity.this, "简介不可为空", Toast.LENGTH_LONG).show();
				release.setEnabled(true);
				return;
			} else {
				supplyDemandDescInfo.setIntroduction(introduction.getText().toString().trim());
			}
			
			if (keywords.getText().toString().trim() == null || keywords.getText().toString().trim().equals("")) {
				Toast.makeText(PublishSupplyActivity.this, "关键字不可为空", Toast.LENGTH_LONG).show();
				release.setEnabled(true);
				return;
			} else {
				supplyDemandDescInfo.setKeyWords(keywords.getText().toString().trim());
			}
			
			if (productInfo.getText().toString().trim() == null || productInfo.getText().toString().trim().equals("") ) {
				Toast.makeText(PublishSupplyActivity.this, "详细内容不可为空", Toast.LENGTH_LONG).show();
				release.setEnabled(true);
				return;
			} else {
				supplyDemandDescInfo.setDescription(productInfo.getText().toString().trim());
			}
			
			if (enterpriseId == 0) {
				Toast.makeText(PublishSupplyActivity.this, "未获取到有效单位ID", Toast.LENGTH_LONG).show();
				release.setEnabled(true);
				return;
			} else {
				supplyDemandDescInfo.setEnterpriseID(enterpriseId);
			}
			
			if (date == null || date.equals("")) {
				Toast.makeText(PublishSupplyActivity.this, "请选择截止日期", Toast.LENGTH_LONG).show();
				release.setEnabled(true);
				return;
			} else {
				supplyDemandDescInfo.setTimeDown(date);
			}
			
			supplyDemandDescInfo.setTypeCode(0);
			supplyDemandDescInfo.setStatus(0);
			
			supplyDemandDescInfo.setMaterialFullName(selectedEnterpriseMaterial.getMaterialFullName());
			supplyDemandDescInfo.setMaterialID(selectedEnterpriseMaterial.getMaterialID());
			supplyDemandDescInfo.setMaterialName(selectedEnterpriseMaterial.getMaterialName());
			
			try {
				List<PicturesInfo> picInfos =picGrid.getList();
				
				fPhotoInfos = new ArrayList<FPhotoInfo>();
				
				if (picInfos == null || picInfos.size() == 0) {
					
				} else {
					for (int i = 0; i < picInfos.size(); i++) {
						PicturesInfo picturesInfo = picInfos.get(i);
						FPhotoInfo info = new FPhotoInfo();
						info.setPhotoName(picturesInfo.getPureName());
						info.setPhotoDescription(picturesInfo.getDescription());
						info.setPhotoPathNormal(picturesInfo.getPureName());
						info.setPhotoPathSmall(picturesInfo.getSurl());
						fPhotoInfos.add(info);
					}
					supplyDemandDescInfo.setPhotoList(fPhotoInfos);
				}
			} catch (Exception e) {
				Toast.makeText(PublishSupplyActivity.this, "图片未保存成功", Toast.LENGTH_LONG).show();
				e.printStackTrace();
			}
			
			progressDialog = ProgressDialog.show(PublishSupplyActivity.this,
					getString(R.string.alert_title),
					getString(R.string.alert_message), true, false);
			
			ReleaseSupplyAsyn releaseSupplyAsyn = new ReleaseSupplyAsyn();
			releaseSupplyAsyn.execute(supplyDemandDescInfo);
			
		}
		
	};
	
	/**
	 * 我的供应按钮点击事件
	 */
	public Button.OnClickListener myReleasesBtnCallback = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			IntegrateQuestInfo integrateQuestInfo = new IntegrateQuestInfo();
			integrateQuestInfo.setEnterpriseID(enterpriseId);
			
			progressDialog = ProgressDialog.show(PublishSupplyActivity.this,
					getString(R.string.alert_title),
					getString(R.string.alert_message), true, false);
			
			MYReleasesSupplyAsyn releasesSupplyAsyn = new MYReleasesSupplyAsyn();
			releasesSupplyAsyn.execute(integrateQuestInfo);
		}
		
	};
	
	/**
	 * 时间选择按钮点击事件
	 */
	public Button.OnClickListener dateBtnCallback = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			showDialog(0);
		}
		
	};
	
	/**
     * 创建日期及时间选择对话框
     */
    @Override
    protected Dialog onCreateDialog(int id) {
    	Dialog dialog = null;
        switch (id) {
        case 0:
            Calendar c = Calendar.getInstance();
            dialog = new DatePickerDialog(
                this,
                new DatePickerDialog.OnDateSetListener() {
                    public void onDateSet(DatePicker dp, int year,int month, int dayOfMonth) {
                    	
                        Date curDate = new Date(System.currentTimeMillis());
                       /* int i = curDate.getYear() + 1900;
                        int j = curDate.getMonth() + 1;
                        int k = curDate.getDate();*/
                        if (year > (curDate.getYear() + 1900)) {
                        	datePicker.setText(year + "-" + (month+1) + "-" + dayOfMonth);
                            date = year + "-" + (month+1) + "-" + dayOfMonth;
						} else if (year == (curDate.getYear() + 1900)) {
							if ((month+1) > (curDate.getMonth() + 1)) {
								datePicker.setText(year + "-" + (month+1) + "-" + dayOfMonth);
	                            date = year + "-" + (month+1) + "-" + dayOfMonth;
							} else if ((month+1) == (curDate.getMonth() + 1)) {
								if (dayOfMonth >= curDate.getDate()) {
									datePicker.setText(year + "-" + (month+1) + "-" + dayOfMonth);
		                            date = year + "-" + (month+1) + "-" + dayOfMonth;
								} else {
									Toast.makeText(PublishSupplyActivity.this, getString(R.string.date_error), Toast.LENGTH_LONG).show();
								}
							} else {
								Toast.makeText(PublishSupplyActivity.this, getString(R.string.date_error), Toast.LENGTH_LONG).show();
							}
						} else {
							Toast.makeText(PublishSupplyActivity.this, getString(R.string.date_error), Toast.LENGTH_LONG).show();
						}
                    }
                }, 
                c.get(Calendar.YEAR), // 传入年份
                c.get(Calendar.MONTH), // 传入月份
                c.get(Calendar.DAY_OF_MONTH) // 传入天数
            );
            break;
        }
		return dialog;
    	
    }
    
    
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == 0 || requestCode == 1) {
				//和之前的图片区分, 这个需求大图和小图都要上传
				picGrid.onViewResult(requestCode, resultCode, data,2,2);
			} 
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	private void showFinishDialog(String s,String string){
    	new AlertDialog.Builder(PublishSupplyActivity.this).setTitle(s)
		.setMessage(string).setPositiveButton("确定", new DialogInterface.OnClickListener() {
	
			@Override
			public void onClick(DialogInterface dialog, int which) {
				PublishSupplyActivity.this.finish();
			}
		}).create().show();
    }
	
	/**
	 * 发布异步
	 * @author Maniac
	 * 2012.12.12
	 */
	private class ReleaseSupplyAsyn extends MyAsyncTask{

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(PublishSupplyActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(PublishSupplyActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					SupplyDemandResultInfo supplyDemandResultInfo = (SupplyDemandResultInfo)Utils.fromJSON(string, SupplyDemandResultInfo.class);
					int result = supplyDemandResultInfo.getResult();
					if (result == 6110) {
						Toast.makeText(PublishSupplyActivity.this, supplyDemandResultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
						PublishSupplyActivity.this.finish();
						Utils.randomAnim(PublishSupplyActivity.this);
					} else {
						Toast.makeText(PublishSupplyActivity.this, supplyDemandResultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
					}
				}
			}
			release.setEnabled(true);
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			SupplyDemandDescInfo request = (SupplyDemandDescInfo)params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(6100, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}
	
	/**
	 * 查看我的供应列表
	 * @author Maniac
	 * 2012.12.12
	 */
	private class MYReleasesSupplyAsyn extends MyAsyncTask{

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(PublishSupplyActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(PublishSupplyActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					
					SupplyDemandResultInfo supplyDemandResultInfo = (SupplyDemandResultInfo)Utils.fromJSON(string, SupplyDemandResultInfo.class);
					int result = supplyDemandResultInfo.getResult();
					if (result == 6510) {
						/*Intent intent = new Intent(PublishSupplyActivity.this,MySupplyListActivity.class);
						intent.putExtra("myReleases", string);
						startActivity(intent);*/
						PublishSupplyActivity.this.finish();
						Utils.randomAnim(PublishSupplyActivity.this);
					} else {
						Toast.makeText(PublishSupplyActivity.this, supplyDemandResultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			
			IntegrateQuestInfo request = (IntegrateQuestInfo)params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(6500, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
		
	}
}
